﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AtDevice
{
    public class GSMInterface : IGSMInterface
    {
        AtDevice _device;

        public GSMInterface(AtDevice device)
        {
            _device = device;
        }

        public string GetIMEI()
        {
            return _device.ExecuteCommand(new AtCommand("CGSN")).GetPlainText();
        }        

        public string GetNetwork()
        {
            // set the format to return long alphanumeric (0) network name
            _device.ExecuteCommand(new AtCommand("COPS").AppendInt(3).AppendInt(0));
            return _device.ExecuteCommand(new AtCommand("COPS?")).GetString(2);
        }
        
        public string GetCellId()
        {
            try {
                return _device.ExecuteCommand(new AtCommand("CREG?")).GetString(3);
            }
            // In case the CREG command doesn't return the cell id
            catch(IndexOutOfRangeException)
            {
                return null;
            }
        }
        
        public bool IsRoamed()
        {
            return _device.ExecuteCommand(new AtCommand("SYSINFO", true)).GetInt(2) == 1;
        }
        
        public NetworkEnum GetNetworkType()
        {
            int type = _device.ExecuteCommand(new AtCommand("SYSINFO", true)).GetInt(3);
            switch(type)
            {
            case 0:
                return NetworkEnum.NoSignal;
            case 3:
                return NetworkEnum.GprsNetwork;
            case 5:
                return NetworkEnum.WcdmaNetwork;
            default:
                AtLogger.LogInfo(String.Format("Warning: Unknown network type received from AT^SYSINFO: {0}", type));
                return NetworkEnum.NoSignal;
            }
        }

        public string GetIMSI()
        {
            return _device.ExecuteCommand(new AtCommand("CIMI")).GetPlainText();
        }

        public string GetICCID()
        {
            return _device.ExecuteCommand(new AtCommand("CCID")).GetPlainText();
        }

        public void ChangePIN(string currentPin, string newPin)
        {
            throw new NotImplementedException();
        }

        public string GetManufacturer()
        {
            return _device.ExecuteCommand(new AtCommand("GMI")).GetPlainText();
        }

        public string GetModel()
        {
            return _device.ExecuteCommand(new AtCommand("GMM")).GetPlainText();
        }

        public string GetModelRevision()
        {
            return _device.ExecuteCommand(new AtCommand("GMR")).GetPlainText();
        }

        public double GetSignal()
        {
            AtResponse response = _device.ExecuteCommand(new AtCommand("CSQ"));
            int signal = response.GetInt(0);

            if (signal == 99)
                throw new UnknownSignalException();

            return signal * 100 / 31;
        }
    }
}
